package crmdna.mail;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

import javax.servlet.http.*;

import crmdna.mail.MailMessage.*;

@SuppressWarnings("serial")
public class SendMailServlet extends HttpServlet {
	
	public void doOptions(HttpServletRequest req, HttpServletResponse resp)
	        throws IOException {
	    resp.setHeader("Access-Control-Allow-Origin", "*");
	    resp.setHeader("Access-Control-Allow-Methods", "POST");
	    resp.setHeader("Access-Control-Allow-Headers", "Content-Type");
	    resp.setHeader("Access-Control-Max-Age", "86400");
	    resp.setHeader("Allow", "POST, OPTIONS");
	}
	
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {

        resp.setHeader("Access-Control-Allow-Origin", "*");
		resp.setContentType("application/json");

		ArrayList<MailContact> contacts = new ArrayList<MailContact>();
		
		for(int i = 0; ;i++)
		{
			String emailAddress = req.getParameter("contacts[" + i + "][EmailAddress]");
			
			if(emailAddress == null) break;
			
			contacts.add(new MailContact(
					req.getParameter("contacts[" + i + "][FirstName]"), 
					req.getParameter("contacts[" + i + "][LastName]"),
					emailAddress));
		}
		
		MailMessage.sendMail(contacts, req.getParameter("vendor"), req.getParameter("subject"), req.getParameter("htmlContent"));
	}
}
